<!--
 * @Author: 黄达全
 * @Date: 2024-07-29 14:36:59
 * @LastEditTime: 2024-08-11 00:17:31
-->
<script lang="ts" setup>
import imageClassification from "@/components/imageClassification.vue"
import groupOfPictures from "@/components/groupOfPictures.vue"
import drawer from "@/components/drawer.vue"
import { ref, reactive, computed, watch, nextTick } from "vue"
import ImageApi from "@/api/model/image"
import useElementPlus from "@/hooks/useElementPlus"
import uploadImage from "@/components/uploadImage.vue"
import type { ImageUploadResponse, UploadImageVO, ElSelectCategoryList, ImagePageItem } from "@/common/type"
import type { FormRules } from 'element-plus'
import { ElForm } from 'element-plus'
import useComRef from "@/hooks/useComRef"

const { is_dialog, height: dialogHeight,multiple } = defineProps({
    is_dialog: {
        type: Boolean,
        default: false
    },
    height: {

        type: Number,
        default: 0
    },
    multiple:{
        type:Boolean,
        default:false
    }
})

const height = is_dialog ? (dialogHeight - 60.67) : document.documentElement.clientHeight - (44.33 + 42 + 60.67 + 14);

const { message } = useElementPlus()

// 添加图片分类
const pictureDrawerRef = ref()
const categoryForm = reactive({
    name: "",
    order: 1
})
// 打开弹窗
const addPictureCategory = () => {
    categoryForm.name = ""
    categoryForm.order = 1
    pictureDrawerRef.value.open()
}
const imageClassificationRef = ref()
const addPictureSubmitHandle = async () => {
    const { code } = await ImageApi.add(categoryForm)
    if (code == 1) {
        imageClassificationRef.value.getCategoryData()
        message({
            message: "新增图片分类成功",
            type: "success"
        })
    }
    pictureDrawerRef.value.close()
}

// 上传图片
const uploadImageList = ref<UploadImageVO[]>([])
const uploadForm = reactive({
    imageCategory: ""
})
const uploadDrawerRef = ref()
const uploadFormRef = useComRef(ElForm)
const uploadImageRef = ref()
const uploadPicture = () => {
    uploadForm.imageCategory = ""
    uploadImageList.value = []
    getImageCategory()
    if (!uploadFormRef) return;
    uploadFormRef.value?.resetFields()
    uploadDrawerRef.value.open()
    nextTick(() => {
        uploadImageRef.value!.clearFiles()
    })
}

// 选择图片
const uploadSuccessHandle = (e: ImageUploadResponse) => {
    const { response } = e
    uploadImageList.value.push({
        name: response[0].name,
        url: response[0].url,
    })

}

// 选择分类
const imageCategoryList = ref<ElSelectCategoryList[]>([])
const getImageCategory = async () => {
    const { data } = await ImageApi.select()
    imageCategoryList.value = data.map((item) => {
        return {
            label: item.name,
            value: item.id
        }
    })
}
getImageCategory()

// 提交
const uploadRules = reactive<FormRules<typeof uploadForm>>({
    imageCategory: [
        { required: true, message: '请选择图片分类', trigger: 'change' },
    ],
})
const uploadSubmitHandle = async () => {
    if (!uploadFormRef) return
    const valid = await uploadFormRef.value!.validate().catch(err => console.log(err))
    if (!valid) return
    // 插入
    const response = await ImageApi.addImageByCategory(uploadImageList.value, Number(uploadForm.imageCategory))
    if (response.code == 1) {
        getCategoryDataHandle()
        message({
            message: "上传成功",
            type: "success"
        })
    }
    uploadDrawerRef.value.close()
}


// 获取对应分类的数据
const page = ref(1)
const pageSize = ref(12)
const imageList = ref<ImagePageItem[]>([])
const imageTotal = ref<number>(0)
const imageId = computed(() => {
    return imageClassificationRef.value?.active
})
watch(imageId, () => {
    page.value = 1
    getCategoryDataHandle()
})
const getCategoryDataHandle = async () => {
    const { code, data } = await ImageApi.getImageByCategoryByPage(imageId.value, page.value, pageSize.value)
    if (code == 1) {
        imageList.value = data.records
        imageTotal.value = data.total
    }
}

const getCategoryDataByPage = (e: number) => {
    page.value = e ? e : page.value
    getCategoryDataHandle()
}

// 选中的图片
type ImagePageItem_Check = ImagePageItem & { checked: boolean }
const selectedImageList = ref<ImagePageItem_Check[]>([])
const emits = defineEmits(["update:modelValue"])
const setAddStatus = (image: ImagePageItem_Check) => {
    if(!multiple && selectedImageList.value.length>0) {
        image.checked=false
        return message({
            message: "只能选择一张图片",
            type: "warning"
        })
    }
    selectedImageList.value.push(image)
    emits("update:modelValue", selectedImageList.value)
}

const setDeleteStatus = (image: ImagePageItem_Check) => {
    selectedImageList.value = selectedImageList.value.filter(item => item.id != image.id)
    emits("update:modelValue", selectedImageList.value)
}

// 清空选中状态数组
const clearCheckStatus = () => {
    selectedImageList.value = []
    console.log(selectedImageList.value);
    
    emits("update:modelValue", selectedImageList.value)
}

const groupOfPicturesRef = ref()
const init_checked = () => {
    // 清空选中状态数组
    clearCheckStatus()
    // 所有图片的状态全为false
    groupOfPicturesRef.value.init_checked()
}

defineExpose({
    init_checked
})

</script>

<template>
    <div class="imagePage">
        <el-card class="card" :body-style="{ height: height + 'px', padding: 0 }">
            <template #header>
                <div class="card-header">
                    <el-button color="var(--primary-theme-color)" icon="el-icon-plus" size="small" type="primary"
                        @click="addPictureCategory">新增图片分类</el-button>
                    <el-button icon="el-icon-UploadFilled" size="small" type="success"
                        @click="uploadPicture">上传图片</el-button>
                </div>
            </template>
            <div class="card-body">
                <div class="card-body-left">
                    <image-classification ref="imageClassificationRef" />
                </div>
                <div class="card-body-right">
                    <groupOfPictures :is_dialog="is_dialog" :imageList="imageList" :total="imageTotal"  :pageSize="12" :currentPage="page"
                        @next-page="getCategoryDataByPage" @check-add-change="setAddStatus"
                        @check-delete-change="setDeleteStatus" ref="groupOfPicturesRef" />
                </div>
            </div>
        </el-card>
        <drawer ref="pictureDrawerRef" title="新增图片分类" direction="ttb" size="20%" @submit="addPictureSubmitHandle">
            <template #ttb>
                <el-form label-width="80px" :inline="true">
                    <el-form-item label="分类名称">
                        <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input-number v-model="categoryForm.order" :min="1" />
                    </el-form-item>
                </el-form>
            </template>
        </drawer>
        <drawer ref="uploadDrawerRef" title="图片上传" direction="rtl" size="35%" @submit="uploadSubmitHandle">
            <template #rtl>
                <div class="select-category">
                    <div class="label">图库分类：</div>
                    <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules">
                        <el-form-item prop="imageCategory">
                            <el-select-v2 v-model="uploadForm.imageCategory" :options="imageCategoryList"
                                placeholder="请选择分类" />
                        </el-form-item>
                    </el-form>
                </div>
                <upload-image @success="uploadSuccessHandle" ref="uploadImageRef" />
            </template>
        </drawer>
    </div>
</template>



<style lang="scss" scoped>
.imagePage {
    width: 100%;
    height: 100%;

    .card {
        height: 100%;

        .card-body {
            height: 100%;
            display: flex;

            .card-body-left {
                width: 220px;
                height: 100%;
                border-right: 1px solid #D9D9D9;
            }

            .card-body-right {
                flex: 1;
                height: 100%;
            }
        }
    }
}

.select-category {
    display: flex;
    height: 35px;
    align-items: center;
    margin-bottom: 20px;

    .label {
        width: 70px;
        font-size: 14px;
    }
}

.el-form {
    height: 35px;
    flex: 1;
    display: flex;
    align-items: center;
}

.el-form-item {
    width: 100%;
    margin-bottom: 0;
}
</style>
